package com.kingsalert.kingsalert.dialog;

import static com.kingsalert.kingsalert.config.PermissionConfig.*;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.viewpager2.widget.ViewPager2;

import com.kingsalert.kingsalert.R;
import com.kingsalert.kingsalert.adapter.PermissionViewAdapter;
import com.kingsalert.kingsalert.bean.PermissionInfo;
import com.kingsalert.kingsalert.listener.PermissionListener;
import com.kingsalert.kingsalert.util.http.HttpUtil;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class PermissionDialog extends Dialog implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private static boolean isShow = false;

    private ViewPager2 viewPager2;
    private PermissionViewAdapter permissionViewAdapter;
    private final ArrayList<PermissionInfo> infos = new ArrayList<>();

    private final ArrayList<View> pointViews = new ArrayList<>();

    private final Context context;

    private final Runnable processRunnable;

    private final String page = "DIALOG_PERMISSION";

    public PermissionDialog(@NonNull Context context, @NonNull Runnable processRunnable) {
        super(context);
        this.context = context;
        this.processRunnable = processRunnable;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_permission);

        setCancelable(false);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setCanceledOnTouchOutside(false);
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        getWindow().setBackgroundDrawableResource(R.color.transparent);

        viewPager2 = findViewById(R.id.dialog_permission_vp_page);
        LinearLayout pointLayout = findViewById(R.id.dialog_permission_layout_diangroup);

        boolean isFirst = true;
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS)){
            infos.add(new PermissionInfo(
                    R.drawable.img_permission_sms,
                    getContext().getString(R.string.permission_sms_title),
                    getContext().getString(R.string.permission_sms_text),
                    smsPermissionListneer,
                    "DIALOG_PERMISSION_SMS")
            );

            View pv = LayoutInflater.from(context).inflate(R.layout.view_blank,null);
            pv.setBackgroundResource(R.drawable.bg_permission_point_true);
            isFirst = false;
            pointViews.add(pv);
            pointLayout.addView(pv);

            infos.add(new PermissionInfo(
                    R.drawable.img_permission_applist,
                    getContext().getString(R.string.permission_applist_title),
                    getContext().getString(R.string.permission_applist_text),
                    applistPermissionListneer,
                    "DIALOG_PERMISSION_APPS")
            );

            View pv1 = LayoutInflater.from(context).inflate(R.layout.view_blank,null);
            pv1.setBackgroundResource(R.drawable.bg_permission_point_false);
            pointViews.add(pv1);
            pointLayout.addView(pv1);

        }

        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context,Manifest.permission.READ_PHONE_STATE)){
            infos.add(new PermissionInfo(
                    R.drawable.img_permission_phone_state,
                    getContext().getString(R.string.permission_phonestate_title),
                    getContext().getString(R.string.permission_phonestate_text),
                    phonestatePermissionListneer,
                    "DIALOG_PERMISSION_PHONE_STATE")
            );

            View pv = LayoutInflater.from(context).inflate(R.layout.view_blank,null);
            if (isFirst) pv.setBackgroundResource(R.drawable.bg_permission_point_true);
            else pv.setBackgroundResource(R.drawable.bg_permission_point_false);
            pointViews.add(pv);
            pointLayout.addView(pv);
        }

        permissionViewAdapter = new PermissionViewAdapter(getContext(),infos);
        viewPager2.setAdapter(permissionViewAdapter);

        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                for (int i = 0 ; i<pointViews.size(); i++){
                    View v = pointViews.get(i);
                    if (i==position) v.setBackgroundResource(R.drawable.bg_permission_point_true);
                    else v.setBackgroundResource(R.drawable.bg_permission_point_false);
                }
            }
        });

    }

    private final PermissionListener smsPermissionListneer = new PermissionListener() {
        @Override
        public void onPermissionAgree() {

            HttpUtil.getInstance().saveBuriedPoint(page,"SMS_AGREE_CLICK","");

            Runnable agreeRunnable = () -> {
                if (context instanceof Activity)
                    EasyPermissions.requestPermissions((Activity) context, context.getString(R.string.launch_permissions_sms), PermissionCode_Sms, Manifest.permission.READ_SMS);
            };

            PermissionViewAdapter.PermissionDialogHolder holder = permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).getHolder();

            if (holder.getCheck()) agreeRunnable.run();
            else {
                new PermissionAgreeDialog(context,() -> {
                    HttpUtil.getInstance().saveBuriedPoint(page,"SMS_CHECKBOX_DIALOG_NO_CLICK","");
                },() -> {
                    HttpUtil.getInstance().saveBuriedPoint(page,"SMS_CHECKBOX_DIALOG_YES_CLICK","");
                    holder.setCheck(true);
                    agreeRunnable.run();
                }).show();
            }

        }

        @Override
        public void onPermissionDeny() {
            HttpUtil.getInstance().saveBuriedPoint(page,"SMS_DENY_CLICK","");
            nextPage();
        }
    };

    private final PermissionListener applistPermissionListneer = new PermissionListener() {
        @Override
        public void onPermissionAgree() {

            HttpUtil.getInstance().saveBuriedPoint(page,"APPS_AGREE_CLICK","");

            Runnable agreeRunnable = () -> {
                permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).setViewAgree();
                nextPage();
            };

            PermissionViewAdapter.PermissionDialogHolder holder = permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).getHolder();

            if (holder.getCheck()) agreeRunnable.run();
            else {
                new PermissionAgreeDialog(context,() -> {
                    HttpUtil.getInstance().saveBuriedPoint(page,"APPS_CHECKBOX_DIALOG_NO_CLICK","");
                },() -> {
                    HttpUtil.getInstance().saveBuriedPoint(page,"APPS_CHECKBOX_DIALOG_YES_CLICK","");
                    holder.setCheck(true);
                    agreeRunnable.run();
                }).show();
            }
        }

        @Override
        public void onPermissionDeny() {
            HttpUtil.getInstance().saveBuriedPoint(page,"APPS_DENY_CLICK","");
            nextPage();
        }
    };

    private final PermissionListener phonestatePermissionListneer = new PermissionListener() {
        @Override
        public void onPermissionAgree() {

            HttpUtil.getInstance().saveBuriedPoint(page,"PHONE_STATE_AGREE_CLICK","");

            Runnable agreeRunnable = () -> {
                if (context instanceof Activity)
                    EasyPermissions.requestPermissions((Activity) context, context.getString(R.string.launch_permissions_phonestate), PermissionCode_PhoneState, Manifest.permission.READ_PHONE_STATE);
            };

            PermissionViewAdapter.PermissionDialogHolder holder = permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).getHolder();

            if (holder.getCheck()) agreeRunnable.run();
            else {
                new PermissionAgreeDialog(context,() -> {
                    HttpUtil.getInstance().saveBuriedPoint(page,"PHONE_STATE_CHECKBOX_DIALOG_NO_CLICK","");
                },() -> {
                    HttpUtil.getInstance().saveBuriedPoint(page,"PHONE_STATE_CHECKBOX_DIALOG_YES_CLICK","");
                    holder.setCheck(true);
                    agreeRunnable.run();
                }).show();
            }
        }

        @Override
        public void onPermissionDeny() {

            HttpUtil.getInstance().saveBuriedPoint(page,"PHONE_STATE_DENY_CLICK","");

            if (context!=null && context instanceof Activity) {
                dismiss();
                ((Activity)context).finish();
            }
        }
    };

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        switch (requestCode){
            case PermissionCode_PhoneState:

                HttpUtil.getInstance().saveBuriedPoint(page,"PHONE_STATE_2_DENY_CLICK","");

                if (EasyPermissions.somePermissionPermanentlyDenied((Activity) context, perms)) {
                    new AppSettingsDialog.Builder((Activity) context).build().show();
                }else {
                    dismiss();
                    ((Activity)context).finish();
                }
                break;
            case PermissionCode_Sms:

                HttpUtil.getInstance().saveBuriedPoint(page,"SMS_2_DENY_CLICK","");

                if (EasyPermissions.somePermissionPermanentlyDenied((Activity) context, perms)) {
                    new AppSettingsDialog.Builder((Activity) context).build().show();
                }else {
                    nextPage();
                }
                break;
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        switch (requestCode){
            case PermissionCode_PhoneState:

                HttpUtil.getInstance().saveBuriedPoint(page,"PHONE_STATE_2_AGREE_CLICK","");

                permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).setViewAgree();
                nextPage();
                break;
            case PermissionCode_Sms:

                HttpUtil.getInstance().saveBuriedPoint(page,"SMS_2_AGREE_CLICK","");

                permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).setViewAgree();

                if (infos.get(0).getHolder()!=null) nextPage();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {}

    @Override
    public void onRationaleAccepted(int requestCode) {
        switch (requestCode){
            case PermissionCode_PhoneState:
                if (context instanceof Activity)
                    EasyPermissions.requestPermissions((Activity) context, context.getString(R.string.launch_permissions_phonestate), PermissionCode_PhoneState, Manifest.permission.READ_PHONE_STATE);
                break;
            case PermissionCode_Sms:
                if (context instanceof Activity)
                    EasyPermissions.requestPermissions((Activity) context, context.getString(R.string.launch_permissions_sms), PermissionCode_Sms, Manifest.permission.READ_SMS);
                break;
        }
    }

    @Override
    public void onRationaleDenied(int requestCode) {

    }

    public void nextPage(){
        int nextPageIndex = viewPager2.getCurrentItem()+1;

        if (nextPageIndex>=0&&permissionViewAdapter.getItemCount()>nextPageIndex) viewPager2.setCurrentItem(nextPageIndex);
        else if (processRunnable!=null) processRunnable.run();
    }

    @Override
    public void show() {
        if (isShow) return;
        isShow = true;
        HttpUtil.getInstance().saveBuriedPoint(page,"START","");
        super.show();
    }

    @Override
    public void dismiss() {
        isShow = false;
        HttpUtil.getInstance().saveBuriedPoint(page,"END","");
        super.dismiss();
    }

}
